package com.ztgf.order.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.base.Joiner;
import com.ztgf.common.utils.CustomizeUtil;
import com.ztgf.order.common.config.YmlConfig;
import com.ztgf.order.mapper.OrderContractRelationMapper;
import com.ztgf.order.models.bo.OrderBusinessContractBO;
import com.ztgf.order.models.bo.OrderContractCenterBO;
import com.ztgf.order.models.bo.OrderContractRelationSaveBO;
import com.ztgf.order.models.dto.OrderContractEnclosureDTO;
import com.ztgf.order.models.dto.OrderContractRelationDTO;
import com.ztgf.order.models.dto.OrderInfoDTO;
import com.ztgf.order.models.dto.OrderStatusDTO;
import com.ztgf.order.models.enums.OrderStateEnum;
import com.ztgf.order.models.service.IOrderContractEnclosureService;
import com.ztgf.order.models.service.IOrderContractRelationService;
import com.ztgf.order.models.service.IOrderInfoService;
import com.ztgf.order.models.service.IOrderStatusService;
import com.ztgf.order.models.vo.OrderBusinessContractVO;
import com.ztgf.order.models.vo.OrderContractCenterVO;
import com.ztgf.shopping.models.service.shop.IShopQiyuesuoInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


/**
 * 订单合同关系表控制器
 *
 * @author chenyu.wang
 * @Date 2020-06-03 15:58:52
 */
@Slf4j
@DubboService
@Lazy
public class OrderContractRelationServiceImpl extends ServiceImpl<OrderContractRelationMapper, OrderContractRelationDTO> implements IOrderContractRelationService {

    @Resource
    private YmlConfig ymlConfig;

    @DubboReference
    private IShopQiyuesuoInfoService shopQiyuesuoInfoService;

    @Autowired
    private OrderContractRelationMapper orderContractRelationMapper;

    @Autowired
    private IOrderInfoService orderInfoService;

    @Autowired
    private IOrderStatusService orderStatusService;
    @Autowired
    private IOrderContractEnclosureService orderContractEnclosureService;

    /**
     * 修改合同
     *
     * @param param
     * @param orderId
     */
    @Override
    public String updateByOrderId(String param, Long orderId, byte[] bytes) throws IOException {
        OrderInfoDTO orderInfoDTO = orderInfoService.selectById(orderId);
        OrderContractRelationDTO orderContractRelationDTO = getByOrderId(orderId);
        // 原合同id
        long contractId = Long.parseLong(orderContractRelationDTO.getContractId());
        log.info("原合同id:{}", contractId);
        shopQiyuesuoInfoService.cancelContact(contractId, 0);//废弃合同
        // 根据订单id和原合同id获取合同是否存在附件
        Wrapper<OrderContractEnclosureDTO> wrapperA = new EntityWrapper<>();
        wrapperA.eq("order_id", orderId);
        wrapperA.eq("caontract_id", contractId);
        List<OrderContractEnclosureDTO> list = orderContractEnclosureService.selectList(wrapperA);
        String annex = "";
        List<String> listA = new ArrayList<>();
        if (CustomizeUtil.listIsNotNull(list)) {
            for (OrderContractEnclosureDTO enclosureDTO : list) {
                listA.add(enclosureDTO.getFileUrl());
            }
            annex = Joiner.on(",").join(listA);
        }
        String contactId = shopQiyuesuoInfoService.promoteContract(orderInfoDTO.getBuyShopId(),
                orderInfoDTO.getSellShopId(), orderId, param, bytes, annex);//合同id
        String contractUrl = shopQiyuesuoInfoService.getContractString(Long.parseLong(contactId));
        if (null == orderId)
            throw new RuntimeException("没有此订单关系");
        OrderContractRelationDTO updateDto = new OrderContractRelationDTO();
        updateDto.setContractId(contactId);
        updateDto.setFileUrl(contractUrl);
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("order_id", orderId);
        update(updateDto, wrapper);//更新合同id
        return contractUrl;
    }

    /**
     * 根据订单id查询
     *
     * @param orderId
     * @return
     */
    @Override
    public OrderContractRelationDTO getByOrderId(Long orderId) {
//        OrderContractRelationDTO orderContractRelationDTO = new OrderContractRelationDTO();
//        orderContractRelationDTO.setOrderId(orderId);
//        return orderContractRelationMapper.selectOne(orderContractRelationDTO);
        Wrapper<OrderContractRelationDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("order_id", orderId);
        return this.selectOne(wrapper);
    }

    /**
     * 根据合同id查询 订单信息
     *
     * @param contractId
     * @return
     */
    @Override
    public OrderInfoDTO getOrderInfoByContractId(Long contractId) {
        return orderContractRelationMapper.getOrderInfoByContractId(contractId);
    }

    @Override
    public Page<OrderBusinessContractVO> queryBusinessContractList(OrderBusinessContractBO bo, Integer contactState) {
        Page<OrderBusinessContractVO> pages = new Page<>(bo.getPageNo(), bo.getPageSize());
        List<OrderBusinessContractVO> list = baseMapper.queryBusinessContractList(pages, bo, contactState);
        pages.setRecords(list);
        return pages;
    }

    @Override
    public boolean add(OrderContractRelationSaveBO saveBO) {
        OrderContractRelationDTO dto = new OrderContractRelationDTO();
        BeanUtils.copyProperties(saveBO, dto);
        Long id = ymlConfig.getPkId();
        dto.setId(id);
        return this.insert(dto);
    }

    public Long addAndReturnId(OrderContractRelationSaveBO saveBO) {
        OrderContractRelationDTO dto = new OrderContractRelationDTO();
        BeanUtils.copyProperties(saveBO, dto);
        Long id = ymlConfig.getPkId();
        dto.setId(id);
        this.insert(dto);
        return id;
    }

    @Override
    public Page<OrderContractCenterVO> queryMyContractList(OrderContractCenterBO bo, Integer contactType) {
        Page<OrderContractCenterVO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        page.setRecords(baseMapper.queryMyContractList(page, bo, contactType));
        return page;
    }

    /**
     * 获取合同地址根据订单id
     *
     * @param orderId
     * @return
     */
    @Override
    public String getContractByOrderId(Long orderId) {
        Wrapper<OrderContractRelationDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("order_id", orderId);
        OrderContractRelationDTO orderContractRelationDTO = selectOne(wrapper);
        if (null == orderContractRelationDTO)
            return "";
        return shopQiyuesuoInfoService.getContractString(Long.parseLong(orderContractRelationDTO.getContractId()));
    }


    /**
     * 获取签署地址根据订单id
     *
     * @param orderId
     * @return
     */
    @Override
    public String getSignaturePage(Long orderId, Long id, int type, String orderIds, Long contractId) {
        log.info("---0---------------orderId="+orderId+"-----------contractId="+contractId+"----------id="+id);
        OrderInfoDTO orderInfoDTO = orderInfoService.selectById(orderId);
        if (null == orderInfoDTO)
            return "";
        OrderContractRelationDTO orderContractRelationDTO = new OrderContractRelationDTO();
        if (null == contractId) {
            Wrapper<OrderContractRelationDTO> wrapper = new EntityWrapper<>();
            wrapper.eq("order_id", orderId);
            orderContractRelationDTO = selectOne(wrapper);
            if (null == orderContractRelationDTO)
                return "";
        } else {
            orderContractRelationDTO.setContractId(contractId + "");
        }
        OrderStatusDTO orderStatusDTO = orderStatusService.getByOrderId(orderId);
        int signType = 0;
        if (orderInfoDTO.getBuyShopId().equals(id)) {//买家签署
            log.info("---1---------------orderId="+orderId);
            //买家合同签订中
            signType = 1;
            if (orderStatusDTO.getContactState() == OrderStateEnum.ORDER_CONTACT_STATE_NO_SIGN.getCode()) {
                orderStatusDTO.setContactState(OrderStateEnum.ORDER_CONTACT_STATE_BUYER_SIGNING.getCode());
            }
        } else {
            log.info("---2---------------orderId="+orderId);
            //卖家合同签订中
            signType = 2;
            if (orderStatusDTO.getContactState() == OrderStateEnum.ORDER_CONTACT_STATE_BUYER_SIGN.getCode()) {
                orderStatusDTO.setContactState(OrderStateEnum.ORDER_CONTACT_STATE_SELLER_SIGNING.getCode());
            }
        }
        orderStatusService.updateById(orderStatusDTO);

        return shopQiyuesuoInfoService.getSignaturePage(id, Long.parseLong(orderContractRelationDTO.getContractId()), type, orderIds, signType);
    }

    /**
     * 获取废弃合同签署地址根据订单id
     *
     * @param orderId  订单id
     * @param shopId   店铺id
     * @param signType 1买家签订 2卖家签订
     * @return
     */
    @Override
    public String getAbandonSignaturePage(Long orderId, Long shopId, int signType) {
        OrderContractRelationDTO orderContractRelationDTO = getByOrderId(orderId);
        Long contractId = Long.parseLong(orderContractRelationDTO.getContractId());
        OrderStatusDTO orderStatusDTO = orderStatusService.getByOrderId(orderId);
        if (signType == 1) {//买家签订
            orderStatusDTO.setBuyerContactAbandonState(1);
        } else {//卖家签订
            orderStatusDTO.setSellerContactAbandonState(1);
        }
        orderStatusService.updateById(orderStatusDTO);
        return shopQiyuesuoInfoService.getAbandonSignaturePage(shopId, contractId, signType);
    }
}
